package org.dxy.infrastructure.persistent.db.mybatispuls.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.dxy.domain.port.IdGenerator;
import org.springframework.stereotype.Service;
import org.dxy.infrastructure.persistent.db.mybatispuls.po.query.RouteProcessViewPo;
import org.dxy.infrastructure.persistent.db.mybatispuls.mapper.RouteProcessViewMapper;
import org.dxy.infrastructure.persistent.db.mybatispuls.service.RouteProcessViewService;

import java.util.ArrayList;
import java.util.List;

/**
 * 工艺工序关系查询视图服务实现
 */
@Service
@RequiredArgsConstructor
public class RouteProcessViewServiceImpl extends ServiceImpl<RouteProcessViewMapper, RouteProcessViewPo> implements RouteProcessViewService {
    private  final IdGenerator idGenerator;
    @Override
    public boolean removeByRouteId(Long routeId) {
        LambdaQueryWrapper<RouteProcessViewPo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RouteProcessViewPo::getRouteId, routeId);
        return remove(wrapper);
    }
    
    @Override
    public boolean saveRouteProcesses(Long routeId, List<Long> processIds) {
        if (processIds == null || processIds.isEmpty()) {
            return true;
        }
        
        List<RouteProcessViewPo> entities = new ArrayList<>();
        for (int i = 0; i < processIds.size(); i++) {
            RouteProcessViewPo entity = RouteProcessViewPo.builder()
                    .id(idGenerator.generate())
                    .routeId(routeId)
                    .processId(processIds.get(i))
                    .stepOrder(i + 1) // 步骤顺序从1开始
                    .build();
            entities.add(entity);
        }
        
        return saveBatch(entities);
    }
    
    @Override
    public List<RouteProcessViewPo> listByRouteId(Long routeId) {
        LambdaQueryWrapper<RouteProcessViewPo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RouteProcessViewPo::getRouteId, routeId)
               .orderByAsc(RouteProcessViewPo::getStepOrder);
        return list(wrapper);
    }
}